/*
 * @lc app=leetcode.cn id=142 lang=golang
 *
 * [142] 环形链表 II
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func detectCycle(head *ListNode) *ListNode {
	if head == nil {
		return nil
	}

	i, j := head, head
	for j != nil && j.Next != nil {
		i = i.Next
		j = j.Next.Next
		if i == j {
			i = head
			for i != j {
				i = i.Next
				j = j.Next
				if i == j {
					break
				}
			}
			return i
		}
	}
	return nil
}

// @lc code=end

